﻿using System;
using System.Drawing;
using System.IO;

namespace GenerateMarkdown
{

    public class Base64File
    {
        public static string GetBase64(string filePath)
        {
            try
            {
                string strPic;
                //读图片转为Base64String
                System.Drawing.Bitmap bmp1 = new System.Drawing.Bitmap(Path.Combine(filePath));
                using (MemoryStream ms1 = new MemoryStream())
                {
                    bmp1.Save(ms1, System.Drawing.Imaging.ImageFormat.Jpeg);
                    byte[] arr1 = new byte[ms1.Length];
                    ms1.Position = 0;
                    ms1.Read(arr1, 0, (int)ms1.Length);
                    ms1.Close();
                    strPic = Convert.ToBase64String(arr1);
                }
                return strPic;
            }
            catch (Exception ex)
            {

                throw ex;
            }
        }


        public static string GetBase64(Image image)
        {
            try
            {
                byte[] bt = null;
                if (!image.Equals(null))
                {
                    using (MemoryStream mostream = new MemoryStream())
                    {
                        Bitmap bmp = new Bitmap(image);
                        bmp.Save(mostream, System.Drawing.Imaging.ImageFormat.Png);//将图像以指定的格式存入缓存内存流
                        bt = new byte[mostream.Length];
                        mostream.Position = 0;//设置留的初始位置
                        mostream.Read(bt, 0, Convert.ToInt32(bt.Length));
                    }
                }
                string strPic = Convert.ToBase64String(bt); //64位图片
                return strPic;
            }
            catch (Exception ex)
            {

                throw ex;
            }
        }
    }
}
